﻿using System.Globalization;

namespace System
{
    public static class DateTimeExtensions
    {
        /// <summary>
        ///  Returns a string representing of a <see cref="DateTime"/> relative value.
        /// </summary>
        /// <param name="dateTime">The <see cref="DateTime"/></param>
        /// <returns>The string value of relative time.</returns>
        public static string ToLocalRelativeTime(this DateTime dateTime)
        {
            if (dateTime <= DateTime.MinValue)
            {
                return "未知时间";
            }
            TimeSpan diff = DateTime.Now - dateTime;
            string suffix = string.Empty;
            int numeral = 0;

            if (diff.TotalDays >= 365)
            {
                numeral = (int)Math.Floor(diff.TotalDays / 365);
                suffix = "年前";
            }
            else if (diff.TotalDays >= 31)
            {
                numeral = (int)Math.Floor(diff.TotalDays / 31);
                suffix = "个月前";
            }
            else if (diff.TotalDays >= 7)
            {
                numeral = (int)Math.Floor(diff.TotalDays / 7);
                suffix = "周前";
            }
            else if (diff.TotalDays >= 1)
            {
                numeral = (int)Math.Floor(diff.TotalDays);
                suffix = "天前";
            }
            else if (diff.TotalHours >= 1)
            {
                numeral = (int)Math.Floor(diff.TotalHours);
                suffix = "小时前";
            }
            else if (diff.TotalMinutes >= 1)
            {
                numeral = (int)Math.Floor(diff.TotalMinutes);
                suffix = "分钟前";
            }
            else if (diff.TotalSeconds >= 30)
            {
                numeral = (int)Math.Floor(diff.TotalSeconds);
                suffix = "秒前";
            }
            else
            {
                suffix = "刚刚";
            }

            string output = numeral == 0 ? suffix : string.Format(CultureInfo.InvariantCulture, "{0} {1}", numeral, suffix);
            return output;
        }

    }
}
